<template>
  <el-row style="padding: 5px">
    <el-row>
      <el-card>
        <el-form :inline="true" :model="recordParams" class="" size="small">
          <el-form-item label="溯源码">
            <el-input v-model="recordParams.traceCode" placeholder="请输入溯源码"></el-input>
          </el-form-item>
          <el-form-item label="查询城市">
            <el-input v-model="recordParams.queryCity" placeholder="请输入查询城市"></el-input>
          </el-form-item>
          <el-form-item label="查询日期">
            <el-date-picker
              v-model="dateTime"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="selectRecordData">搜索</el-button>
            <el-button type="" icon="el-icon-refresh-right" @click="resetForm">重置</el-button>
          </el-form-item>
          <el-form-item style="float: right">
            <el-button type="primary" plain icon="el-icon-plus"  @click="addRecordData(1)" v-hasPermi="['agriculture:record:add']">新增</el-button>
            <el-button type="warning" plain icon="el-icon-download">导出</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </el-row>
    <el-row style="margin-top: 5px">
      <el-card>
        <el-table :data="tableData.slice((currentPage -1) *pageSize,currentPage*pageSize)" border style="width: 100%">
          <el-table-column align="center" prop="traceCode" label="溯源码" ></el-table-column>
          <el-table-column align="center" prop="queryDate" label="查询时间" ></el-table-column>
          <el-table-column align="center" prop="queryCity" label="城市"></el-table-column>
          <el-table-column align="center" prop="queryAddress" label="详细地址"></el-table-column>
        </el-table>
        <el-pagination
          style="margin: 20px 0; float: right"
          :current-page.sync="currentPage"
          background
          :page-size="pageSize"
          layout="total, prev, pager, next, jumper"
          :total="this.tableData.length">
        </el-pagination>
      </el-card>
    </el-row>

    <el-dialog  :visible.sync="this.dialog" width="30%">
      <template v-slot:title>
        <div style="color: black;font-weight:1000; font-size: 20px;">{{dialogTitle}}</div>
      </template>
      <el-form :model="this.addRecord">
        <el-form-item  :label-width="300">
          <template v-slot:label><i class="el-icon-star-on" style="font-size: 10px ;color: red"></i>溯源产品</template>
          <el-select v-model="addRecord.sellproId" placeholder="请选择溯源产品" style="width: 70%" @change="selectCode">
            <el-option v-for="item in sellproOptions"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item  :label-width="300">
          <template v-slot:label><i class="el-icon-star-on" style="font-size: 10px ;color: red"></i>查询时间</template>
          <el-date-picker
            v-model="addRecord.queryDate"
            type="date"
            placeholder="选择日期"
            align="right"
            :picker-options="pickerOptions"
            style="width: 70%">
          </el-date-picker>
        </el-form-item>
        <el-form-item  :label-width="300">
          <template v-slot:label><i class="el-icon-star-on" style="font-size: 10px ;color: red"></i>溯源码</template>
          <el-select v-model="addRecord.traceCode" placeholder="请选择溯源码" style="width: 70%;margin-left: 15px" :no-data-text="ondataText">
            <el-option v-for="item in codeOptions"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item  :label-width="300">
          <template v-slot:label><i class="el-icon-star-on" style="font-size: 10px ;color: red"></i>查询地点</template>
          <el-input v-model="addRecord.queryAddress" placeholder="请输入查询地点" autocomplete="off" style="width:70%">
            <el-button slot="append" :icon="this.iconDate" @click="popover"></el-button>
          </el-input>
        </el-form-item>
        <el-form-item :label-width="300">
          <template v-slot:label><i class="el-icon-star-on" style="font-size: 10px ;color: red"></i>查询坐标</template>
          <el-input v-model="addRecord.queryCoordinate" placeholder="请选择查询坐标" autocomplete="off" style="width:70%"></el-input>
          <el-popover
            placement="right" trigger="manual" width="530" v-model="popoverVisible">
            <BaiduMap chart-width="500px" chart-height="300px" @coordinateClicked="handleCoordinateClicked"></BaiduMap>
          </el-popover>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog=false">取 消</el-button>
        <el-button type="primary" @click="handleButtonClick">确 定</el-button>
      </div>
    </el-dialog>
  </el-row>
</template>
<script>
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import Template from "@/views/iot/template/index.vue";
import {listRecord,addRecord,updateRecord} from "@/api/agriculture/record";
import {listSellpro} from "@/api/agriculture/sellpro";
import BaiduMap from "@/views/agriculture/record/MapCharts/baiduMap.vue";
import {listCode} from "@/api/agriculture/code";
export default {
  components: {Template,BaiduMap},
  data() {
    const initialAddData={
      sellproId:'',
      traceCode:'',
      queryDate:'',
      queryAddress:'',
      queryCoordinate:'',
      queryCity:'',
      cityCode:'',
      remark:'',
      status:'',
      orderNum:'',
    }
    return {
      ondataText:'请先选择产品',
      iconDate:'el-icon-location',
      popoverVisible: false,
      sellproOptions:'',
      codeOptions:'',
      pickerOptions:{
        shortcuts:'',
      },
      recordParams:{
        traceCode:'',
        params:{beginQueryDate:'', endQueryDate:'',},
        queryAddress:'',
        queryCity:'',
      },
      sellproParams:{
        sellproName:'',
        sellproArea:'',
        sellproWeight:'',
        sellproGuige:'',
        sellproImg:'',
        germplasmId:'',
        batchId:'',
        landId:'',
        deviceId:'',
        cameraId:'',
        staffId:'',
        shopId:'',
        h5Url:'',
        status:'',
        orderNum:'',
      },
      codeParams:{
        traceCode:'',
        versionId:'',
        sellproId:'',
      },
      addRecord:{...initialAddData},
      initialAddData,
      dateTime:'',
      dialogTitle:'',
      dialog:false,
      currentPage:1,
      pageSize:10,
      tableData: [],
      requiredFields:{  sellproId:'请选择产品',  queryDate:'请选择查询时间',traceCode:'请输入溯源码',  queryAddress:'请选择查询地点',queryCoordinate:'请获取坐标'}
    }
  },
  async mounted() {
    await this.getRecordList()
    this.optionDate()
  },

  methods:{
    async selectCode(){
      this.codeParams.sellproId=this.addRecord.sellproId
      const row1 = await listCode(this.codeParams)
      if(row1.total>0)
      {
      this.codeOptions = row1.rows.map(item => ({
        value: item.traceCode,
        label: item.traceCode
      }));
      } else{
        this.ondataText='当前产品无溯源码，请先生成溯源码！'
      }
    },
    // 百度地图数据
    handleCoordinateClicked({ cityName, provinceName, address, coordinates }) {
    this.addRecord.queryCity=cityName,
    this.addRecord.queryAddress=address
    this.addRecord.queryCoordinate=coordinates
    this.iconDate='el-icon-success'
    },
    popover() {
      this.popoverVisible = !this.popoverVisible
      if(this.popoverVisible)
      {
        this.iconDate='el-icon-remove'
      }
      if(!this.popoverVisible)
      {
        this.iconDate='el-icon-location'
      }
    },
    // 对话框确定按钮选择监听修改或新增
    handleButtonClick() {
      if (this.addOrUpdate === 1) {
        this.updateRecordData(this.addRecord,2)
      } else {
        this.addRecordData(2);
      }
    },
    // 警告消息
    openMessage(type,mes) {
      this.$notify({
        title: '提示',
        message: mes,
        offset: 30,
        type: type
      });
    },
    // 化时间日期
    changeTime(originalDateString){
      const originalDate = new Date(Date.parse(originalDateString));
      const year = originalDate.getFullYear();
      const month = String(originalDate.getMonth() + 1).padStart(2, '0');
      const day = String(originalDate.getDate()).padStart(2, '0');
      const hours = String(originalDate.getHours()).padStart(2, '0');
      const formattedDateString = `${year}-${month}-${day}`;
      return formattedDateString;
    },
    // 时间快捷选择
    optionDate(){
      const  shortcuts=[{
        text: '今天',
        onClick(picker) {
        picker.$emit('pick', new Date());
      }
    }, {
        text: '昨天',
          onClick(picker) {
          const date = new Date();
          date.setTime(date.getTime() - 3600 * 1000 * 24);
          picker.$emit('pick', date);
        }
      }, {
        text: '一周前',
          onClick(picker) {
          const date = new Date();
          date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
          picker.$emit('pick', date);
        }
      }]
      this.pickerOptions.shortcuts=shortcuts
    },
    // 获取列表
    async getRecordList(){
      const row =await listRecord(this.recordParams)
      const row2 = await listSellpro(this.sellproParams)
      this.sellproOptions = row2.rows.map(item => ({
        value: item.sellproId,
        label: item.sellproName
      }));
      this.tableData =row.rows
    },
    // 新增
    async addRecordData(buttonId)
    {
      if(buttonId == 1) {this.addRecord= { ...this.initialAddData };this.dialogTitle ='添加溯源码查询记录';this.dialog= true; this.addOrUpdate = 0}
      else if(buttonId == 2) {
        for (let field of Object.keys(this.requiredFields)) {
          if (!this.addRecord[field]) {
            this.openMessage('warning', this.requiredFields[field]);
            return;
          }
        }
        try {
          await addRecord(this.addRecord)
          this.openMessage('success', '添加成功！');
          await this.getRecordList()
          this.addRecord={...this.initialAddData}
          this.dialog = false
        } catch (error) {
          console.error('添加溯源码查询记录错误:', error);
          this.openMessage('error', '添加失败！');
        }
      }
    },
    // 修改溯源人员
    async updateRecordData(row,buttonId)
    {
      if(buttonId == 1) {this.addRecord= {...row} ;this.dialogTitle ='修改溯源码查询记录';this.dialog=true;this.addOrUpdate = 1 }
      else if(buttonId == 2){
        for (let field of Object.keys(this.requiredFields)) {
          if (!this.addStaff[field]) {
            this.openMessage('warning', this.requiredFields[field]);
            return;
          }
        }
        try {
          await updateRecord(this.addRecord)
          this.openMessage('success', '修改成功！');
          await this.getRecordList()
          this.dialog = false
        }catch (error){
          console.error('Error occurred while update sellpro:', error);
          this.openMessage('error', '修改失败！');
        }
      }
    },
    // 查询
    async selectRecordData(){
     if(this.dateTime)
     {
       this.recordParams.params.beginQueryDate=this.changeTime(this.dateTime[0])
       this.recordParams.params.endQueryDate=this.changeTime(this.dateTime[1])
     }
      await this.getRecordList()
    },
    // 重置
    async resetForm(){
      this.recordParams.traceCode='',
      this.recordParams.queryAddress='',
      this.recordParams.queryCity='',
      this.recordParams.params.beginQueryDate='',
      this.recordParams.params.endQueryDate='',
      await this.getRecordList()
    }

  }
}
</script>
<style scoped>
.mini_Button{
  font-size:11px;
  padding: 4px 9px
}
</style>
